package com.example.tang.zhayan.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tang.zhayan.BaseApp;
import com.example.tang.zhayan.R;
import com.example.tang.zhayan.adapter.ShopBagAdapter;
import com.example.tang.zhayan.bean.DbBuyDetail;
import com.example.tang.zhayan.pay.PayDemoActivity;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 购物袋界面
 * Created by tang on 2015/12/18.
 */
@ContentView(R.layout.activity_shop_bag)
public class ShopBagActivity extends AppCompatActivity implements View.OnClickListener {
    @ViewInject(R.id.iv_bag_back)
    private ImageView imgBack;
    @ViewInject(R.id.ptr_shop_bag)
    private PullToRefreshListView ptrListView;
    @ViewInject(R.id.tv_shop_empty)
    private TextView textEmpty;
    @ViewInject(R.id.btn_shop_pay)
    private Button btnPay;
    @ViewInject(R.id.cb_shop_top)
    private CheckBox cbDelete;
    @ViewInject(R.id.cb_shop_all)
    private CheckBox cbAll;
    @ViewInject(R.id.rl_shop_bottom)
    private RelativeLayout rlBottom;
    @ViewInject(R.id.tv_shop_totalMoney)
    private TextView textAliiPrice;
    private boolean isDelete;
    private List<DbBuyDetail> listAll;
    private ShopBagAdapter shopBagAdapter;
    private boolean isSelected = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        listAll = new ArrayList<>();
        EventBus.getDefault().register(this);
        //选择删除 或者 结算
        changeSelected();
        //全选的按钮
        selectAll();

        //进来的时候进行查询
        selectAllPrice();
        //从数据库里面查询并且添加数据
        try {
            if (BaseApp.getApp().getDb().findAll(DbBuyDetail.class) != null) {
                listAll.addAll(BaseApp.getApp().getDb().findAll(DbBuyDetail.class));
            }

            if (shopBagAdapter != null) {
                shopBagAdapter.notifyDataSetChanged();
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

        checkedIsEmpty();
        //绑定适配器
        shopBagAdapter = new ShopBagAdapter(this, listAll);
        ptrListView.setAdapter(shopBagAdapter);

        //ptrListView的点击事件
        ptrListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckBox checkBox = (CheckBox) view.findViewById(R.id.cb_shop_bg);
                if (!checkBox.isChecked()) {
                    checkBox.setChecked(true);
                    EventBus.getDefault().post("allPrice", "totalPrice");
                } else {
                    checkBox.setChecked(false);

                    EventBus.getDefault().post("allPrice", "deletePrice");
                }

            }
        });

        //返回的监听事件
        imgBack.setOnClickListener(this);
        btnPay.setOnClickListener(this);
    }

    private void selectAllPrice() {
        int sum = 0;

        try {
            List<DbBuyDetail> allPrice = BaseApp.getApp().getDb().findAll(DbBuyDetail.class);
            if (allPrice != null) {
                for (int i = 0; i < allPrice.size(); i++) {
                    if (allPrice.get(i).getFlag() == 1) {
                        sum += Integer.parseInt(allPrice.get(i).getPrice().substring(1)) * Integer.parseInt(allPrice.get(i).getCurrentCount());
                    }
                }
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
        textAliiPrice.setText("￥" + sum + ".0");
    }

    private void checkedIsEmpty() {
        //判断是数据是否为空 如果是空的就显示购物栏为空 否则显示购物车里的商品
        if (listAll.size() == 0) {
            textEmpty.setVisibility(View.VISIBLE);
            ptrListView.setVisibility(View.GONE);
            rlBottom.setVisibility(View.GONE);
        } else {
            textEmpty.setVisibility(View.GONE);
            ptrListView.setVisibility(View.VISIBLE);
            rlBottom.setVisibility(View.VISIBLE);
        }
    }


    private void selectAll() {
        cbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    for (int i = 0; i < listAll.size(); i++) {
                        listAll.get(i).setFlag(1);
                        DbBuyDetail dbBuyDetail = listAll.get(i);
                        try {
                            BaseApp.getApp().getDb().saveOrUpdate(dbBuyDetail);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        shopBagAdapter.notifyDataSetChanged();
                    }
                    EventBus.getDefault().post("allPrice", "totalPrice");
                } else {
                    for (int i = 0; i < listAll.size(); i++) {
                        listAll.get(i).setFlag(0);
                        DbBuyDetail dbBuyDetail = listAll.get(i);
                        try {
                            BaseApp.getApp().getDb().saveOrUpdate(dbBuyDetail);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        shopBagAdapter.notifyDataSetChanged();
                    }
                    EventBus.getDefault().post("allPrice", "deletePrice");
                }

            }
        });
    }

    /**
     * 显示你所有购买物品的总价格
     *
     * @param str
     */
    @Subscriber(tag = "totalPrice")
    public void getToatalNum(String str) {
        int sum = 0;
        if (!str.equals("")) {
            try {
                List<DbBuyDetail> allPrice = BaseApp.getApp().getDb().findAll(DbBuyDetail.class);
                for (int i = 0; i < allPrice.size(); i++) {
                    if (allPrice.get(i).getFlag() == 1) {
                        sum += Integer.parseInt(allPrice.get(i).getPrice().substring(1)) * Integer.parseInt(allPrice.get(i).getCurrentCount());
                    }
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
        textAliiPrice.setText("￥" + sum + ".0");
    }


    /**
     * 显示你所有购买物品的总价格
     *
     * @param str
     */
    @Subscriber(tag = "deletePrice")
    public void getDeleteNum(String str) {
        int sum = 0;
        if (!str.equals("")) {
            try {
                List<DbBuyDetail> allPrice = BaseApp.getApp().getDb().findAll(DbBuyDetail.class);
                for (int i = 0; i < allPrice.size(); i++) {
                    if (allPrice.get(i).getFlag() == 1) {
                        sum += Integer.parseInt(allPrice.get(i).getPrice().substring(1)) * Integer.parseInt(allPrice.get(i).getCurrentCount());
                    }
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
        textAliiPrice.setText("￥" + sum + ".0");
    }

    /**
     * 选择在结算或者是删除
     */
    private void changeSelected() {
        //  删除/结算  选择
        cbDelete.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    btnPay.setBackgroundResource(R.drawable.bg_shopbtn_red);
                    btnPay.setText(R.string.stringShopActivityDelete);
                    isDelete = true;
                } else {
                    btnPay.setBackgroundResource(R.drawable.bg_shop_button);
                    btnPay.setText(R.string.stringShopBagActivityPay);
                    isDelete = false;
                }
            }
        });
    }

    /**
     * 删除选中项
     */
    private void deleteChecked() {
        try {
            for (int i = 0; i < listAll.size(); i++) {
                if (listAll.get(i).getFlag() == 1) {
                    BaseApp.getApp().getDb().delete(listAll.get(i));
                    listAll.remove(i);
                    shopBagAdapter.notifyDataSetChanged();
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_bag_back:
                this.finish();
                break;
            case R.id.btn_shop_pay:
                if (isDelete) {
                    EventBus.getDefault().post("1", "buy");
                    for (int i = 0; i < listAll.size(); i++) {
                        if (listAll.get(i).getFlag() == 1) {
                            try {
                                BaseApp.getApp().getDb().delete(listAll.get(i));
                                listAll.remove(i);
                                shopBagAdapter.notifyDataSetChanged();
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    checkedIsEmpty();
                } else {
                    Intent intent = new Intent(this, PayDemoActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
